package com.guli.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guli.base.exception.GuliException;
import com.guli.edu.entity.Subject;
import com.guli.edu.entity.excel.SubjectExcelData;
import com.guli.edu.service.SubjectService;

public class SubjectExcelListener extends AnalysisEventListener<SubjectExcelData> {

    // excel监听器无法交给spring管理 所以传SubjectService进来
    private SubjectService subjectService;

    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectExcelData subjectExcelData, AnalysisContext analysisContext) {
        if (subjectExcelData == null){
            throw new GuliException(20001, "添加失败");
        }
        // 添加一级分类
        // 技巧点 不存在就新建一条数据，存在就拿出来 利用其id添加二级分类
        Subject existOneSubject = this.existOneSubject(subjectService, subjectExcelData.getOneSubjectName());
        if (existOneSubject == null) {      // 第一次添加
            existOneSubject = new Subject();
            existOneSubject.setTitle(subjectExcelData.getOneSubjectName());
            existOneSubject.setParentId("0");
            subjectService.save(existOneSubject);
        }
        // 一级分类的id当做二级的父id
        String pid = existOneSubject.getId();
        // 添加二级分类
        Subject existTwoSubject = this.existTwoSubject(subjectService, subjectExcelData.getTwoSubjectName(), pid);
        if (existTwoSubject == null) {      // 第一次添加
            existTwoSubject = new Subject();
            existTwoSubject.setTitle(subjectExcelData.getTwoSubjectName());
            existTwoSubject.setParentId(pid);
            subjectService.save(existTwoSubject);
        }

    }

    // 判断一级分类是否重复 从 0 号开始 ，二级分类的parent_id就是一级分类的id
    private Subject existOneSubject(SubjectService subjectService,String oneName){
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", oneName);
        wrapper.eq("parent_id","0");
        return  subjectService.getOne(wrapper);
    }
    // 判断二级分类是否存在      不同一级分类 不能一起比较
    private Subject existTwoSubject(SubjectService subjectService,String twoName,String pid){
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", twoName);
        wrapper.eq("parent_id",pid);
        return subjectService.getOne(wrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {}
}
